import requests
import ddddocr
import re
from bs4 import BeautifulSoup

ocr = ddddocr.DdddOcr(show_ad=False)


# 识别图片数字
def identify(img):
    return ocr.classification(img)


def is_float(offsets):
    for num in offsets:
        if num.find(".") > 0:
            return True

    return False


url = "https://www.ziroom.com/z/"

# 构建请求头
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                  " Chrome/128.0.0.0 Safari/537.36"
}
html = requests.get(url, headers=headers).text  # 获取源代码

bs = BeautifulSoup(html, "lxml")

info_boxes = bs.select("div.Z_list-box div.item div.info-box")

for box in info_boxes:
    try:
        # 获取标题
        title = box.select_one("h5.title.sign a").text
        desc = box.select_one("div.desc div").text

        # 大小  楼层   朝向
        size, floor, toward = desc.split(" | ")

        # 获取位置
        location = box.select_one("div.desc div.location").text.strip()

        """
            获取所有表示价格的节点
        """
        spans = box.select("div.price-content div.price span.num")

        # 获取背景图片
        style = spans[0].get("style")

        url = "https:" + re.findall(r"url\((.*?)\);", style)[0]
        content = requests.get(url).content

        # with open("num.png", "wb") as fp:
        #     fp.write(content)

        # 获取图片对应的数字
        num_str = identify(content)

        # 获取偏移像素
        offsets = []

        for span in spans:
            style = span.get("style")  # 获取样式
            offset = re.findall(r"background-position: (.*?)px", style)[0]
            # index = int(float(offset)/-20)
            # price += num_str[index]

            offsets.append(offset)
        price = ""
        bl = is_float(offsets)
        for offset in offsets:
            if bl:
                index = int(float(offset) / -21.4)
                price += num_str[index]
            else:
                index = int(float(offset) / -20)
                price += num_str[index]

        print(num_str, offsets, price)

    except Exception:
        pass
